<?php

  function db_affected_rows($qry = false) {
  	return (!empty($qry)) ? mysql_affected_rows($qry) : mysql_affected_rows();
  }
	
	

	
  function db_create_table($table = false, $conf_file_path = false)
  {
  	if (empty($conf_file_path)) $conf_file_path = PHPDRIVER . "database_schema/{$table}.ini";
  	
  	//download table config file if necessary...
  	if (!is_file($conf_file_path)) {
  		$conf_file_path = PHPDRIVER . "database_schema/{$table}.ini";
  		if (!is_file($conf_file_path)) {
    		//attempt to download from http://www.phpdriver.org/downloads/database_schema/{$table}.ini
    		$ini = file_get_contents("http://www.phpdriver.org/downloads/database_schema/{$table}.ini");
    		
    		if (!file_put_contents(PHPDRIVER . "database_schema/{$table}.ini", $ini)) echo $php_errormsg;
  		}
  	}
  	
  	//complain if there isn't a table config file
  	if (!file_exists($conf_file_path)) {
  		warning("Cannot create table <em>$table</em> without table ini file: <strong>$conf_file_path</strong>");
  		return false;
  	}					
  
  	if (debug('CREATE_TABLE')) {
    	echo pre(PHPDRIVER . "database_schema/{$table}.ini");
    	echo '<pre>';
    	readfile(PHPDRIVER . "database_schema/{$table}.ini");
    	echo '</pre>';
  	}
  	//parse table config file...
  	$fields = parse_ini_file($conf_file_path, true);
  	if (!$fields) return error("Failed to parse ini file: <strong>$conf_file_path</strong>");
    /*
			ALL TALBES MUST HAVE THIS:
      [ctime]
      type = timestamp
      default = "CURRENT_TIMESTAMP"
    	
      *MOST* TABLES MUST HAVE THIS:
    	[archived]
      type = tinyint
    	length = 1
      default = 0
    	
    	[sort]
      type = int
    	length = 11
      default = 0
    */
  	$fields['ctime'] = array('type' => 'timestamp', 'default' => 'CURRENT_TIMESTAMP');
  	
  	if (!stristr($table, '_to_') && $table != 'conf' && $table != 'user_roles_data_access' && $table != 'user_roles_module_access') {
  		//no need to have these fields in intersection tables or the conf table
    	$fields['archived'] = array('type' => 'tinyint', 'length' => 1, 'default' => 0);
    	$fields['sort'] = array('type' => 'int', 'length' => 11, 'default' => 0);
  	}
  
  	if (debug('CREATE_TABLE')) {
  		printr($fields);
  	}
  	
  	if (in_array($table, db_installed_tables()) || db_table_exists($table)) {
  		warning("$table already exists!");
  		return false;
  	}
  	
    if (debug('CREATE_TABLE')) debug(printr($fields, true));
  	if (array_key_exists('not_ready', $fields)) {
  		information("DB Config file for $table is not ready, please check phpdriver/database_schema/$table.ini");
  		return false;
  	}
  	
    if (empty($fields) || !is_array($fields)) return false;
    if (empty($table)) $table = variable_name($fields);
    if (isset($fields['_keys_'])) {
    	if (empty($keys)) $keys = $fields['_keys_'];
    	unset($fields['_keys_']);
    }
		
		if (isset($fields['_queries_'])) {
			if (empty($queries)) $queries = $fields['_queries_'];
			unset($fields['_queries_']);
		}
  	
  	if (array_key_exists('ctime', $fields)) $keys['index_ctime'] = 'ctime';
  	if (array_key_exists('username', $fields)) $keys['index_username'] = 'username';
  	if (array_key_exists('active', $fields)) $keys['index_active'] = 'active';
  	if (array_key_exists('sort', $fields)) $keys['index_sort'] = 'sort';
    
    message("Creating table: $table.");
		
    $sql = "CREATE TABLE IF NOT EXISTS `$table` (\n";
    foreach ($fields as $field_name => $field) {
  		if ($field['default'] !== 'auto') {
				if (stristr($field['type'], 'int')) $field['default'] = intval($field['default']);
    		elseif (stristr($field['type'], 'float') || stristr($field['type'], 'double')) $field['default'] = floatval($field['default']);
      	elseif (isset($field['default']) && ($field['default'] == NULL || strtolower($field['default']) == 'null')) $field['default'] = '';
			}
  				
    	$sql.= "\t`$field_name` {$field['type']}";
			
    	if (isset($field['length'])) $sql.= "({$field['length']})";
    	
			$sql.= ' ';
			
    	if (!$field['allow_null']) $sql.= "NOT NULL ";
			
    	if ($field['default'] === 'auto') $sql.= "AUTO_INCREMENT";
    	elseif ($field['type'] == 'timestamp') $sql.= "DEFAULT {$field['default']}";
  		elseif (isset($field['default'])) $sql.= "DEFAULT '{$field['default']}'";
  		
  		$sql.= ", \n";
    }
  	
  	
    $i = 0;
    foreach ($keys as $key => $field) {
  		if (substr($key, 0, 5) == 'index') $key = 'index';
  	
    	if (is_array($field)) {
    		foreach ($field as $field_) {
    			$sql.= "\t$key ";
  				if (strtolower($key) != 'index') $sql.= 'KEY ';
    			if (strtolower($key) != 'primary') $sql.= "`$key{$i}` ";
    				if (stristr($field_, ',')) {
    					$sql.= "(";
    					foreach (explode(',', $field_) as $field_name) $sql.= '`' . trim($field_name) . '`, ';
    					$sql = rtrim(rtrim($sql), ',');
    					$sql.= "), \n";
    				} else $sql.= "(`$field_`), \n";
    			$i++;				
    		}
    	} else {
  			$sql.= "\t$key ";
  			if (strtolower($key) != 'index') $sql.= 'KEY ';
    		if (strtolower($key) != 'primary') $sql.= "`$key{$i}` ";
    		if (stristr($field, ',')) {
    			$sql.= "(";
    			foreach (explode(',', $field) as $field_name) $sql.= '`' . trim($field_name) . '`, ';
    			$sql = rtrim(rtrim($sql), ',');
    			$sql.= "), \n";
    		} else $sql.= "(`$field`), \n";
    	}
    	
    	$i++;
    }
    $sql = rtrim(rtrim($sql), ',');
    $sql.= "\n) ENGINE=MyISAM DEFAULT CHARSET=latin1";
  	
  	if (debug('CREATE_TABLE')) debug($sql);
  	
    if (db_query($sql)) {
  		success("Table created: $table.");
			
    	if (!empty($queries['sql'])) {
      	foreach ($queries['sql'] as $sql) {
					if (!db_query($sql)) warning(db_error() . "<pre>$sql</pre><hr />");
				}
      }
  	} else error("Failed to create table: $table.<br />" . db_error() . "<pre>$sql</pre><hr />");
  }



	
  function db_data_seek($qry = false, $row_number = 0)
  {
    if (!is_resource($qry)) return false;
    
    return @mysql_data_seek($qry, $row_number);
  }

	
	
  function db_error()
  {
  	return mysql_error();
  }
  
	
	
  function db_escape_string($str = NULL)
  {
  	return @mysql_real_escape_string($str);
  }
  
	
	
  function db_exists($db = false)
  {
  	if (!$db) return false;
  
  	return db_select_db($db, db_connect());
  }
	
	
	function db_fetch_array($query = false)
	{
		return array_stripslashes(@mysql_fetch_array($qry));
	}
	
  
  function db_fetch_assoc($query = false)
  {
  	return array_stripslashes(@mysql_fetch_assoc($query));
  }
  
	
	
  function db_fetch_row($qry = NULL)
  {
    return array_stripslashes(@mysql_fetch_row($qry));
  }
  
	
	
  function db_field($row_id = false, $table = false, $field = 'name', $insecure = false)
  {
    if (empty($row_id)) return false;
    if (empty($table)) return false;
		
  	if (!$insecure && !authorized($table, 'select', true)) {
    	warning("You do not have sufficient privileges to view $table records.");
      return $record;
    } //eof if auth
    
    $sql = "SELECT `$field` FROM `$table` WHERE id = '$row_id' ORDER BY id ASC LIMIT 1";
    $qry = db_query($sql);
    return db_num_rows($qry) == 1 ? stripslashes(db_result($qry, 0)) : error("Failed to get $field from $table for id: $row_id"); 
  }
  
	
	
  function db_field_exists($field = false, $table = false)
  {
  	if (empty($field)) return false;
  	if (empty($table)) return false;
  
  	$sql = "SHOW COLUMNS FROM $table";
  	$qry = db_query($sql);
  	while ($col = @db_fetch_assoc($qry)) if ($col['Field'] == $field) return true;
   
  	return false;
  }
  
	
	
  function db_field_type($field = false, $table = false) 
  {
  	$sql = "SELECT column_name, data_type FROM information_schema.columns WHERE table_name='{$table}'";
  	$qry = db_query($sql);
    while($table = db_fetch_assoc($qry)) {
    	if($table['column_name'] != $field) continue;
      else return $table['data_type'];
    }
  }
  
	
  
  function db_info($qry = NULL) {
  	return mysql_info($qry);
  }


	
  function db_insert_id()
  {
  	return mysql_insert_id();
  }

	
	
  function db_installed_tables()
  {
  	$sql = "SHOW TABLES FROM `{MYSQL_DATABASE}`";
  	$qry = db_query($sql);
  	$installed_tables = array();
  	while ($row = db_fetch_row($qry)) $installed_tables[] = $row[0];
  	
  	return $installed_tables;
  }	  	
	
	
	
	function db_install_tables()
	{
		foreach (scandir(PHPDRIVER . 'database_schema/') as $file) {
			if ($file == '.' || $file == '..' || file_extension($file) != '.ini') continue;
			$table = basename($file, '.ini');
			
  		if (defined('DROP_TABLES') && DROP_TABLES == true) {
  			message("Dropping table: $table");
  			db_query("DROP TABLE IF EXISTS `$table`") or die(db_error());
  		}
			
			if (!db_table_exists($table)) db_create_table($table);
		}
	}
	
	
	
	function db_num_rows($qry)
	{
		return is_resource($qry) ? mysql_num_rows($qry) : false;
	}

	
	
  function db_optimize_tables($table = false, $mode = false, $show_table_names = false)
  {
  	$_sql = (strtolower($mode) == 'repair')
  				? "REPAIR TABLE `xxxxx` QUICK"
  				: "OPTIMIZE TABLE `xxxxx`";
  	
  	$sql = "SHOW TABLES FROM `{MYSQL_DATABASE}`";
  	if ($table) $sql.= " LIKE '$table'";
  	$qry = db_query($sql);
  	$i = 0;
    while ($row = mysql_fetch_row($qry)) {
  			$i++;
  			
  			if (php_sapi_name() == 'cli') {
    			echo ($show_table_names) ? $row[0] : "Optimization $i";
  				ob_flush();
  				flush();
  				
          db_query(str_replace('xxxxx', $row[0], $_sql));
     			echo mysql_affected_rows() ? ' +OK' : ' -Err';
  				ob_flush();
  				flush();
  				
    			echo "\n";
  				ob_flush();
  				flush();
  			} else {
    			$msg = ($show_table_names) ? $row[0] : "Optimization $i";
  				
  				
          db_query(str_replace('xxxxx', $row[0], $_sql));
     			$msg.= mysql_affected_rows() ? ' +OK' : ' -Err';
  				
    			message($msg);
  			}			
    }
  }
	

	
	function db_query($sql)
  {
  	if (!is_resource($GLOBALS['db_connection'])) {
    	$GLOBALS['db_connection'] = mysql_connect(MYSQL_HOSTNAME, MYSQL_USERNAME, MYSQL_PASSWORD) or die(mysql_error());
    	mysql_select_db(MYSQL_DATABASE) or die(mysql_error());
    }
    
    return mysql_query($sql, $GLOBALS['db_connection']);
  }
  
	
  
  function db_real_escape_string($str = NULL, $cnx = NULL)
  {
  	return @mysql_real_escape_string($str, $cnx);
  }
  
	
	function db_record_exists($record_id = false, $table = false)
	{
		if (!db_table_exists($table)) return false;
		$sql = "SELECT id FROM $table WHERE id = $record_id";
		return db_num_rows(db_query($sql)) == 1;
	}
	
		
		
  function db_result($query = false, $row = NULL, $field = NULL)
  {
  	return @mysql_result($query, $row, $field);
  }



	function db_save($record, $table, $insecure = false)
  {
  	if (empty($table)) {
    	error('You must specify the $record, and the $table when using the db_save() function!');
    	return false;
  	}
    
  	//this function always returns $record (with any modifications it has made) --except on DELETE
  	if (intval($record['id']) == 0) {//inserting a new record
    	if (!$insecure && !authorized($table, 'insert', true)) {
      	warning('You do not have sufficient privileges to create records for this table.');
      	return $record;
      }//eof if auth 
    
    	$sql = "INSERT INTO `$table` (";
      foreach ($record as $field => $value) $sql.= "`$field`, ";
      $sql = rtrim(rtrim($sql), ',');
      $sql.= ') VALUES ('; 
      foreach ($record as $field => $value) $sql.= "'$value', ";
      $sql = rtrim(rtrim($sql), ',');
      $sql.= ')';
      if (db_query($sql)) {
      	$record['id'] = mysql_insert_id();
        return $record;
      } //eof if db_query
    } else {//existing record (i.e. it has an id)
    	if ($record['delete'] === true) {//deleting an existing record
				if (intval($record['id']) <= 0) {
					warning('This record is protected and cannot be deleted. [neg id]');
          unset($record['delete']);
          return db_save($record, 'table');//save the other fields
        }
											
      	if (!$insecure && !authorized($table, 'delete', true)) {
        	warning("You do not have sufficient privileges to delete $table records.");
          unset($record['delete']);
          return db_save($record, 'table');//save the other fields
        } //eof if auth
        
        return db_query("DELETE FROM `$table` WHERE id = '{$record['id']}'");
      } else {//updating an existing record
				if ($record['archive'] == 1) {
  				if (!$insecure && !authorized($table, 'archive', true)) {
          	warning("You do not have sufficient privileges to modify existing $table records.");
  				}//eof if auth
					
					$archive_record = array('id' => $record['id'], 'archive' => 1);
					db_save($archive_record, $table);//save it now, just incase this user cannot update, but can only archive.
					
          unset($record['archive']);//so we can save the rest of the data if authorized.
        } //eof archive
				
      	if (!$insecure && !authorized($table, 'update', true)) {
        	warning("You do not have sufficient privileges to modify existing $table records.");
          return $record;
        } //eof if auth
				
      	$sql = "UPDATE `$table` SET ";
        foreach ($record as $field => $value) {
					$sql.= ($field != 'password')
      				 ? "`$field` = '$value', "
      				 : "`$field` = AES_ENCRYPT('$value', username), ";
				}
        $sql = rtrim(rtrim($sql), ',');
				$sql.= " WHERE id = '{$record['id']}'";
        if (db_query($sql)) return $record;
				else return false;
      }//eof if deleting or updating
    }//eof if new or existing record		
  }//eof function
	

	
	
  function db_select($row_id = false, $table = false, $insecure = false, $flat = false)
  {
  	if (!$insecure && !authorized($table, 'select', true)) {
    	warning("You do not have sufficient privileges to view existing $table records.");
      return $record;
    } //eof if auth
	
    if (is_array($row_id)) $row_id = $row_id['id'];
    if (empty($row_id)) return array('id' => 0);
    
    if (empty($table)) $table = rtrim(variable_name($row_id), '_id');
    
    $sql = "SELECT * FROM `$table` WHERE id = '" . intval($row_id) . "' ORDER BY id ASC LIMIT 1";
    $qry = db_query($sql);
    
    if (is_resource($qry) && db_num_rows($qry) == 1) {
    	$row = db_fetch_assoc($qry);
  		
  		if ($table == 'user') unset($row['password']);
  		
  		foreach ($row as $field => $value) {
  			if ($field == 'record_id') continue;
  			
				if (!$flat) {
    			if (ends_with($field, '_id')) {				
    				$new_table = substr($field, 0, strrpos($field, '_id'));
    				$new_field = singular($new_table);
    				$row[$new_field] = db_select($value, $new_table, $insecure);
    				if ($row[$new_field]['delete'] == 1) unset($row[$new_field]);
    			} elseif (stristr($field, '_id_')) {
    				list($new_table, $_type) = explode('_id_', $field);
    				$new_field = singular($new_table);
    				$row["{$new_field}_{$_type}"] = db_select($value, $new_table, $insecure);
    				if ($row["{$new_field}_{$_type}"]['delete'] == 1) unset($row["{$new_field}_{$_type}"]);
    			}
				}
  		}
			
			//protect passwords
			if (isset($row['password'])) unset($row['password']);
			
    	return $row; 			
    } else return warning("Unable to retreive record_id: $row_id from $table!", __FILE__, __LINE__);
  }

	
  	
  function db_table($table = false, $fields = false, $where = false, $order_by = false, $limit = false, $start = false)
  {
  	if($_REQUEST[$table.'_purge']) {
  		$save['id'] = $_REQUEST[$table."_id"];
    	$save['purge'] = true;
      
      $save = db_save($save, $table);
      success("Record ID: " . $_REQUEST[$table."_id"] . " from table: " . $table . " has been deleted.");
  	}
    $add="";
    foreach($_REQUEST as $key => $Val) {
    	if($key == "dir" ||
         $key == "table" ||
      	 $key == "limit" ||
         $key == "start" ||
         $key == "order_by" ||
         $key == $table . "_id" ||
         $key == $table . "_purge" ||
         $key == "PHPSESSID") continue;
    	$add.= "&".$key."=".$Val;
    }
    
  	if(empty($table)) $table = $_REQUEST['table'];
    if(empty($table)) warning("You must provide a table name to print a list.");
    if(empty($fields)) $fields = array('id','edit');
    if(!is_array($fields)) $fields = array($fields);
    if(empty($limit)) $limit = $_REQUEST['limit'];
    if(empty($start)) $start = $_REQUEST['start']*$limit;
    if(empty($start)) $start = 0;
    if(empty($order_by)) $order_by = $_REQUEST['order_by'];
    if(empty($order_by)) $order_by = "id";
    if(empty($_REQUEST['dir'])) $dir = "ASC";
    else $dir = $_REQUEST['dir'];
    
    $new_dir = ($dir == "ASC") ? "DESC" : "ASC";
    
    $sql = "SELECT ";
    foreach($fields as $field) {
    	if(db_field_exists($field, $table)) $sql.=" `$field`,";
    }
      if(!in_array("id", $fields)) $sql.= " `id`,";
      $sql = rtrim($sql, ",");
    
    $sql.= " FROM `$table` ";
    if(is_array($where) && !empty($where)) {
    	$sql.= "WHERE ";
    	$i;
      foreach($where as $check) {
      	$i++;
        if($i != 1) $sql.= " AND ";
        $sql.= $check;
      }
    } elseif(!empty($where)) $sql.= "WHERE " . $where;
    
    if(!empty($order_by) && is_array($order_by)) {
    
    	$sql.= " ORDER BY ";
      foreach ($order_by as $order) $sql.= $order . " " . $dir . ", ";
      
    	$sql = rtrim($sql, ",");
    } elseif(!empty($order_by)) $sql.= " ORDER BY " . $order_by . " " . $dir . " ";
    
    
    $qry = db_query($sql);
    $number = db_num_rows($qry);
    if($number <= 0) {
    	return "<h3>No Data Found in Table: $table</h3>";
    } else {
    
		if ($limit == 0) $limit = 25;
		
    $pages = ($number/$limit);
    $cur_page = $start/$limit;
    
    if(!empty($limit)) $sql.= "LIMIT $start, $limit";
    
    $qry = db_query($sql);
    ob_start();
    
    if($number >= $limit) {
    ?>
      <?php if($start+$limit > $cur_page*$limit) { ?>
      <div class="numbar">
        <?php if($cur_page > 0) { ?>
        <span>[<a href="?order_by=<?php echo $order_by?>&dir=<?php echo $dir?>&start=<?php echo $cur_page-1?>&limit=<?php echo $limit?><?php echo $add?>">Previous</a>]</span>
        <?php } 
        
        $i = 0;
        if($cur_page > 5) $total = round($cur_page-5);
        else $total = 0;
        
        if($cur_page > 5) echo "&hellip;";
        
      	while($i <= $pages) {
        	if($i >= 10) {
          	?>
            &hellip;
            <?php
          	break;
          }
      	?>
        	<a href="?order_by=<?php echo $order_by?>&dir=<?php echo $dir?>&start=<?php echo $total?>&limit=<?php echo $limit?><?php echo $add?>" <?php if($total == $cur_page) echo "class='current_page'"; ?>><?php echo $total+1?></a>&nbsp;
      	<?php
          $i++;
          $total++;
      	} 
        ?>
        <?php if($start+$limit < $number) { ?>
        [<a href="?order_by=<?php echo $order_by?>&dir=<?php echo $dir?>&start=<?php echo $cur_page+1?>&limit=<?php echo $limit?><?php echo $add?>">Next</a>]
        <?php } ?>
      </div>
      <?php } ?>
    <?php } ?>
    <table cellpadding="0" cellspacing="0" style="width:100%;">
    	<thead>
      	<tr>
    <?php
    	foreach ($fields as $field) {
      	if($field != "edit" && $field != "images_id_default" && $field != 'purge' && db_field_exists($field, $table)) {
        ?>
        <th style="<?php if ($field == 'id') { ?> text-align: center;<?php } ?>"><a href="?order_by=<?php echo $field?>&dir=<?php echo $new_dir?>&start=<?php echo $start?>&limit=<?php echo $limit?><?php echo $add?>"><?php echo ucwords(str_replace('_', ' ', $field))?></a></th>
        <?php
        } else {
        ?>
        <th>&nbsp;</th>
        <?php
        }
      }
    ?>
    		</tr>
    	</thead>
      <tbody>
    <?php
    while($item = db_fetch_assoc($qry)) {
    	if(in_array('edit', $fields)) {
      	$more_info = ' onClick="top.location.href=\'edit?' . $table . '_id=' . $item[id] . '\'"';
      } else unset($more_info);
    	$class = ($class == "light") ? "dark" : "light";
    ?>
    	<tr class="<?php echo $class?>">
  	<?php
    	foreach ($fields as $field) {
      	if($field != "edit" && $field != "images_id_default" && $field != "purge" && db_field_exists($field, $table)) {
          $new_table = substr($field, 0, strpos($field, '_id'));
          if(db_field_type($field, $table) == "tinyint") {
          	if($item[$field] == "1") $item[$field] = "TRUE";
            elseif($item[$field] == "0") $item[$field] = "FALSE";
          } elseif(db_table_exists($new_table)) {
          	if(db_field_exists('name', $new_table)) {
            	$query = db_query("SELECT `name` FROM `$new_table` WHERE `id`='{$item[$field]}' LIMIT 1");
              if($new_item = db_fetch_assoc($query)) {
              	$item[$field] = $new_item['name'];
              }
            } elseif(db_field_exists('first_name', $new_table) && db_field_exists('last_name', $new_table)) {
            	$query = db_query("SELECT `first_name`, `last_name` FROM `$new_table` WHERE `id`='{$item[$field]}' LIMIT 1");
              if($new_item = db_fetch_assoc($query)) {
              	$item[$field] = $new_item['first_name'] . ' ' . $new_item['last_name'];
              }
            }
          }
          ?>
          	<td <?php echo $more_info?> style="cursor:help;<?php if ($field == 'id') { ?> text-align: center;<?php } ?>"><?php echo $item[$field]?></td>
          <?php
        } else {
        	if($field == "edit") {
        ?>
        	<td width="16px">
  				<a href="edit?<?php echo $table?>_id=<?php echo $item['id']?>" class="edit" title="Edit">EDIT</a>
  			</td>
        <?php
        	} elseif($field == "images_id_default") {
            if(!empty($item[$field])) {
            ?>
          	<td>
            <a href="<?php echo PHPDRIVER_WEB?>images/?images_id=<?php echo $item[$field]?>" rel="lightbox-<?php echo $table?>" title="<?php echo $item['name']?>">
            	<img src="<?php echo PHPDRIVER_WEB?>images/?images_id=<?php echo $item[$field]?>&amp;width=40&amp;cropped" width="40" alt="" />
            </a>  
            </td>
          	<?php	
            } else {
            ?>
          	<td>
            	N/A
            </td>
          	<?php	
            }
          } elseif($field == "delete") {
          ?>
          <td width="16px">
          	<?php if($item['id'] > 0) { ?>
          	<a href="delete?<?php echo $table?>_id=<?php echo $item['id']?>" onClick="return confirm('Are you sure you want to delete this record?');" class="delete" title="Delete">Delete</a>
          	<?php } else echo '&nbsp;'; ?>
          </td>
          <?php
          } else {
          ?>
          <td width="16px">
  				<?php if($item['id'] > 0) { ?>
          	<a href="<?php echo $field?>?<?php echo $table?>_id=<?php echo $item['id']?>" class="<?php echo $field?>" title="<?php echo ucwords(str_replace('_', ' ', $field))?>"><?php echo ucwords(str_replace('_', ' ', $field))?></a>
  				<?php } ?>
          </td>
          <?php
          }
        }
      }
    	?>
      </tr>
    <?php
    }
    ?>
      </tbody>
    </table>
    <?php if($number >= $limit) { ?>
      <?php if($start+$limit > $cur_page*$limit) { ?>
      <div class="numbar">
        <?php if($cur_page > 0) { ?>
        <span>[<a href="?order_by=<?php echo $order_by?>&dir=<?php echo $dir?>&start=<?php echo $cur_page-1?>&limit=<?php echo $limit?><?php echo $add?>">Previous</a>]</span>
        <?php } 
        
        $i = 0;
        if($cur_page > 5) $total = round($cur_page/2);
        else $total = 0;
        
        if($cur_page > 5) echo "&hellip;";
        
      	while($i <= $pages) {
        	if($i >= 10) {
          	?>
            &hellip;
            <?php
          	break;
          }
      	?>
        	<a href="?order_by=<?php echo $order_by?>&dir=<?php echo $dir?>&start=<?php echo $total?>&limit=<?php echo $limit?><?php echo $add?>" <?php if($total == $cur_page) echo "class='current_page'"; ?>><?php echo $total+1?></a>&nbsp;
      	<?php
          $i++;
          $total++;
      	} 
        ?>
        <?php if($start+$limit < $number) { ?>
        [<a href="?order_by=<?php echo $order_by?>&dir=<?php echo $dir?>&start=<?php echo $cur_page+1?>&limit=<?php echo $limit?><?php echo $add?>">Next</a>]
        <?php } ?>
      </div>
      <?php } ?>
    <?php } ?>
    <?php
    $html = ob_get_contents();
    ob_clean();
    
    return $html;
    }
  }

	
	
  function db_table_exists($table = false, $db = false)
  {
    if (empty($table)) return false;
    if (stristr($table, '.')) list($db, $table) = explode('.', $table, 2);
    if (empty($db)) $db = MYSQL_DATABASE;
  
  	$sql = "SHOW TABLES FROM `$db` LIKE '$table'";
  	$qry = db_query($sql);
    if (!$qry) warning("Failed to get list of tables from database: $db!", __FILE__, __LINE__);
  
  	while ($row = db_fetch_row($qry)) if ($row[0] == $table) return true;
  
   	return false;
  }



	function db_table_to_table($id1 = 0, $id2 = 0, $intersection_table = false)
  {
  	if (empty($intersection_table)) return false;
  		
  	list($table1, $table2) = explode('_to_', $intersection_table);
  	
  	$sql = "SELECT COUNT(1) FROM $intersection_table WHERE {$table1}_id = '$id1' AND {$table2}_id = '$id2'";
  	$qry = db_query($sql);
  	return db_result($qry, 0) > 0; 
  }
	
	
	
	function debug($item = false)
	{
		if (defined("DEBUG_{$item}")) return constant("DEBUG_{$item}");
		elseif (!empty($item)) echo $item;
		elseif (defined('DEBUG')) return DEBUG;
		else return false;
	}
		
	

  function display_messages($clear = true)
  {	
  	//display messages with actual data in them.
  	if (empty($_SESSION['messages'])) return true;
  	
  	//clear out empty messages
  	foreach ($_SESSION['messages'] as $msg_group => $messages) {
  		foreach ($messages as $idx => $msg) {
  			if (trim($msg) == '') unset($_SESSION['messages'][$msg_group][$idx]);
  		}
  		
  		if (empty($_SESSION['messages'][$msg_group])) unset($_SESSION['messages'][$msg_group]);
  	}
  	
  	## CHECK IF EMPTY ONE MORE TIME --- now that it's cleaned up.
  	//display messages with actual data in them.
  	if (empty($_SESSION['messages'])) return true;
  	
  ?>
  <script type="text/javascript" src="http://cdn.jquerytools.org/1.2.6/full/jquery.tools.min.js"></script>
  <div id="messagebox">
  	<div>
  		<h2>Messages</h2>
    	<div>
    
      <?php
    	foreach ($_SESSION['messages'] as $msg_group => $messages) {
    		foreach ($messages as $idx => $msg) {
      	?>
      		<div class="<?php echo singular($msg_group)?>"><?php echo $msg?></div>
      	<?php
    		}
    	}
    	?>
    		<br />
    	</div>
  		<button class="close">Close</button>
  	</div>
  </div>
  <script type="text/javascript">
  // select the overlay element - and "make it an overlay"
  $("#messagebox").overlay({
  	// custom top position
  	top: 60,
  	// some mask tweaks suitable for facebox-looking dialogs
  	mask: {
  		// you might also consider a "transparent" color for the mask
  		color: '#fff',
  		// load mask a little faster
  		loadSpeed: 200,
  		// very transparent
  		opacity: 0.5
  	},
  	// disable this for modal dialog-type of overlays
  	closeOnClick: true,
  	// load it immediately after the construction
  	load: true
  });
  </script>
  <?php
  /*
  	foreach ($_SESSION['messages'] as $type => $msgs) {
  		$type = ucwords($type);
  		echo "<h4>$type</h4><ul>";
  		foreach ($msgs as $msg) {
  			echo "<li>$msg</li>";
  		}
  		echo "</ul>";
  	}
  */
  
  		
  	if ($clear) unset($_SESSION['messages']);
  }

	
	
  function domain($which = 'domain', $hostname = false)
  {
  	if (empty($hostname)) $hostname = $_SERVER['HTTP_HOST'];
  	$hostname = trim(trim(trim($hostname), '.'));
  
  	$parts = explode('.', $hostname);
  
  	if (count($parts) == 1) return end($parts);
  
  	switch ($which) {
  		case 'tld':
  			return end($parts);
  		break;
  
  		case 'domain':
  			return trim($parts[count($parts)-2] . '.' . end($parts), '.');
  		break;
  
  		case 'host':
  			switch (count($parts)) {
  				case 1:
  				case 2:
  					return false;
  				break;
  
  				default:
  					$out = '';
  					for ($i = 0; $i < (count($parts) - 2); $i++) $out.= $parts[$i] . '.';
  					return trim($out, '.');
  				break;
  			}
  		break;
  
  		default:
  			return $hostname;
  		break;
  	}
  }